package com.bcmusic.pay.controller;

import com.alibaba.fastjson.JSON;
import com.bcmusic.order.pojo.Orders;
import com.bcmusic.pay.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : WeixinPayController  //类名
 * @Description :   //描述
 * @Author : YG  //作者
 * @Date: 2020-10-14 14:30  //时间
 */
@ApiModel(description = "微信支付",value = "pay")
@RestController
@RequestMapping("/pay")
public class WeixinPayController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${mq.pay.exchange.order}")
    private String exchange;
    @Value("${mq.pay.queue.order}")
    private String queue;
    @Value("${mq.pay.routing.key}")
    private String routing;
//    @GetMapping("/test")
//    public Result test(){
//        //动态的从attach参数中获取数据
//        Map<String,String> attach = new HashMap<>();
//        attach.put("username","zhangsan");
//        attach.put("queue","queue.order");//队列名称
//        attach.put("routingkey","queue.order");//路由key
//        attach.put("exchange","exchange.order   ");
//        // {routingkey=queue.seckillorder, exchange=exchange.seckillorder, queue=queue.seckillorder, username=szitheima}
//        rabbitTemplate.convertAndSend(attach.get("exchange"),attach.get("routingkey"),"we are the world");
//
//        return new Result<>(true, StatusCode.OK,"成功");
//    }

    /**
     * 创建二维码路径返回前端，前端生成二维码
     * @param outtradeno 订单id
     * @param money
     * @return
     */
    @ApiOperation(value = "创建支付二维码", notes = "调用该接口创建支付二维码。这个接口由于用的别人的微信api，会导致订单号重复导致error")
    @GetMapping("/create/native")
    public Result<Map> createNative(String orderId,String money){
        //获取用户名
        Map<String,String>parameters=new HashMap<>();
        //订单号容易重复
        parameters.put("out_trade_no",orderId);
        //TODO 改id为string
//        Orders order = (Orders) redisTemplate.boundHashOps("Order").get(Integer.valueOf(orderId));
//        if(order==null)
//        {
//            return new Result<>(true,StatusCode.ERROR,"找不到订单，请重试");
//        }
        //不相信前端数据，在redis缓存中获取
//        money=order.getPaymentAmount();
        BigDecimal bigDecimal=new BigDecimal(money);
        bigDecimal=bigDecimal.multiply(new BigDecimal(100));
        DecimalFormat df=new DecimalFormat("#");
        //微信支付格式是分
        parameters.put("total_fee",df.format(bigDecimal));
        Map<String, String> resultMap = weixinPayService.createNative(parameters);
        if(resultMap.get("code_url")==null)
        {
            return new Result<>(true,StatusCode.ERROR,"生成二维码失败，请稍后再试");
        }
        return new Result<Map>(true, StatusCode.OK, "二维码连接地址创建成功", resultMap);
    }


    /**
     * 接收 微信支付通知的结果  结果(以流的形式传递过来)
     */
    @ApiIgnore
    @RequestMapping("/notify/url")
    public String jieshouResult(HttpServletRequest request) {

        try {
            //1.获取流信息
            ServletInputStream ins = request.getInputStream();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            //todo
            byte[] buffer = new byte[1024];
            int len;
            while ((len = ins.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }

            bos.close();
            ins.close();

            //2.转换成XML字符串
            byte[] bytes = bos.toByteArray();

            //微信支付系统传递过来的XML的字符串
            String resultStrXML = new String(bytes, "utf-8");
            //3.转成MAP
            Map<String, String> map = WXPayUtil.xmlToMap(resultStrXML);

            System.out.println("微信api回调"+resultStrXML);

            //4.发送消息给Rabbitmq  .........
            String data = JSON.toJSONString(map);

            rabbitTemplate.convertAndSend(env.getProperty("mq.pay.exchange.order"),env.getProperty("mq.pay.routing.key"),data);
            //5.返回微信的接收请况(XML的字符串)
            Map<String, String> resultMap = new HashMap<>();
            resultMap.put("return_code", "SUCCESS");
            resultMap.put("return_msg", "OK");
            return WXPayUtil.mapToXml(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 查询支付状态
     * @param outtradeno
     * @return
     */
    @ApiOperation(value = "查询订单状态", notes = "前端在创建支付二维码之后，应该每隔几秒调用这个接口查询状态，如果查询到的状态为已支付，就通知用户")
    @GetMapping("/status/query")
    public Result queryStatus(String outtradeno){
        Map<String,String> resultMap = weixinPayService.queryPayStatus(outtradeno);
        return new Result(true,StatusCode.OK,"查询状态成功！",resultMap);
    }

    /**
     * 关闭微信支付二维码
     * @param outtradeno
     * @return
     * @throws Exception
     */
    @ApiIgnore
    @GetMapping("closePay")
    public Result closePay(@RequestParam String outtradeno)throws Exception
    {
        Map<String, String> map = weixinPayService.closePay(outtradeno);
        return new Result(true,StatusCode.OK,"关闭支付成功",map);
    }
}
